package servlets;


import java.io.IOException;
import java.rmi.RemoteException;
import java.util.HashMap;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import actions.*;

public class ControlServlet extends HttpServlet{
	private static final long serialVersionUID = 1L;

	private HashMap<String,IAction> lesActions;
	private ServletContext sc;

	public void init(ServletConfig c) throws ServletException{
		super.init(c);
		sc = c.getServletContext();
		initActions();
	}

	private void initActions(){
		lesActions = new HashMap<String,IAction>();
		try {
			lesActions.put("accueil", new ActionVoirPageAccueil());
			lesActions.put("pageCateg", new ActionVoirPageProduits());
			lesActions.put("ajouterAuPanier", new ActionAjouterAuPanier());
			lesActions.put("retirerDuPanier", new ActionRetirerDuPanier());
			lesActions.put("supprimerDuPanier", new ActionSupprimerDuPanier());
			lesActions.put("validerConnexion", new ActionValiderConnexion());
			lesActions.put("deconnexion", new ActionDeconnexion());
			lesActions.put("creerCompte", new ActionVoirPageCreerCompte());
			lesActions.put("modifierPanier", new ActionVoirPageModifPanier());
			lesActions.put("passerCommande", new ActionVoirPagePasserCommande());
			lesActions.put("commandeValid", new ActionVoirPageCommandeValid());
			lesActions.put("voirInfosClient", new ActionVoirPageInfosClient());
			lesActions.put("modifierAdresse", new ActionModifierAdresse());
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}

	private IAction getAction(String cmd) throws Exception{
		if(cmd == null) cmd = "accueil";
		IAction c = lesActions.get(cmd);
		if(c == null) throw new Exception("Commande inconnue");
		return c;
	}

	public void doGet(HttpServletRequest req, HttpServletResponse rep){
		String next;
		try{
			IAction action = getAction(req.getParameter("cmd"));
			next=action.execute(req);
		}catch(Exception e){
			//req.setAttribute("erreur", e.getMessage());
			System.out.println("erreur : "+e);
			next ="erreur.jsp";
		}

		RequestDispatcher rd = sc.getRequestDispatcher("/WEB-INF/lesVues/"+next);
		try {
			rd.forward(req, rep);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
